<template>
  <div class="history-wrapper">
    <div class="icon icon-pre" :class="{ canUndo }" @click="handleUnDo" />
    <div class="icon icon-next" :class="{ canRedo }" @click="handleRedo" />
  </div>
</template>

<script setup lang="ts">
import { useDebouncedRefHistory } from '@vueuse/core'
import { type PropType, ref, watch } from 'vue'
import { cloneDeep } from 'lodash-es'

const props = defineProps({
  modelValue: {
    type: Object as PropType<any>,
    required: true
  },
  beforeUpdate: {
    type: Function as PropType<() => void>
  }
})

const emit = defineEmits(['update:modelValue', 'onChange'])
const state = ref<any>(cloneDeep(props.modelValue))

watch(props.modelValue, (value) => {
  state.value = cloneDeep(value)
})

const { history, undo, redo, canRedo, canUndo } = useDebouncedRefHistory<any>(state, {
  deep: true,
  debounce: 100
})

const handleUpdateValue = () => {
  const { snapshot } = history.value[0]
  emit('update:modelValue', snapshot)
  emit('onChange', snapshot)
}

const handleUnDo = () => {
  if (canUndo.value) {
    undo()
    props.beforeUpdate && props.beforeUpdate()
    handleUpdateValue()
  }
}
const handleRedo = () => {
  if (canRedo.value) {
    redo()
    props.beforeUpdate && props.beforeUpdate()
    handleUpdateValue()
  }
}
</script>

<style lang="less" scoped>
.history-wrapper {
  display: flex;
  align-items: center;
  .icon {
    width: 16px;
    height: 16px;
    background-repeat: no-repeat;
    background-size: cover;
    cursor: pointer;
    margin: 0 4px;
  }

  .icon-pre {
    background-image: url('@/assets/images/diy/history-pre-disable.png');

    &.canUndo {
      background-image: url('@/assets/images/diy/history-pre.png');

      &:hover,
      &:active {
        background-image: url('@/assets/images/diy/history-pre-active.png');
        scale: 1.05;
      }
    }
  }

  .icon-next {
    background-image: url('@/assets/images/diy/history-next-disable.png');

    &.canRedo {
      background-image: url('@/assets/images/diy/history-next.png');

      &:hover,
      &:active {
        background-image: url('@/assets/images/diy/history-next-active.png');
        scale: 1.05;
      }
    }
  }
}
</style>
